﻿using ETModel;
using UnityEngine;

namespace ETHotfix {
    [ObjectSystem]
    public class FreeViewUnitCameraComponentAwakeSystem : AwakeSystem<FreeViewUnitCameraComponent> {
        public override void Awake(FreeViewUnitCameraComponent self) {
            self.Awake();
        }
    }

    [ObjectSystem]
    public class FreeViewUnitCameraComponentLateUpdateSystem : LateUpdateSystem<FreeViewUnitCameraComponent> {
        public override void LateUpdate(FreeViewUnitCameraComponent self) {
            self.LateUpdate();
        }
    }

    /// <summary>
    /// 跟随单位并且可以鼠标左键按住旋转视角(附加到场景即可使用)
    /// </summary>
    public class FreeViewUnitCameraComponent : Component {

        /// <summary>
        /// 当前操作的相机
        /// </summary>
        public Camera MainCamera;

        /// <summary>
        /// 相机跟随单位的偏移量,默认是zero
        /// </summary>
        public Vector3 FollowOffset { get; set; } = Vector3.zero;

        /// <summary>
        /// 要跟随的单位
        /// </summary>
        public Unit FollowUnit { get; set; }

        /// <summary>
        /// 鼠标旋转灵敏度,越大越灵敏
        /// </summary>
        public float RotateSpeed { get; set; } = 5.0f;

        public void Awake() {
            MainCamera = Camera.main;

            Vector3 angles = MainCamera.transform.eulerAngles;
            MainCameraAnglesX = angles.y;
            MainCameraAnglesY = angles.x;
        }
        private float MainCameraAnglesX = 0;
        private float MainCameraAnglesY = 0;

        public void LateUpdate() {
            // 摄像机每帧更新位置
            UpdatePosition();

            if (Input.GetMouseButton(0)) {
                //左键按住开始旋转摄像头
                MainCameraAnglesX += Input.GetAxis("Mouse X") * RotateSpeed;
                MainCameraAnglesY -= Input.GetAxis("Mouse Y") * RotateSpeed;
                Quaternion rotation = Quaternion.Euler(MainCameraAnglesY, MainCameraAnglesX, 0.0f);
                MainCamera.transform.rotation = rotation;
            }
        }

        private void UpdatePosition() {
            if (FollowUnit != null && !FollowUnit.IsDisposed) {
                MainCamera.transform.position = FollowUnit.Position + FollowOffset;
            }
        }
    }
}
